class Solution {
    int dx[4] = {0, 0, -1, 1};
    int dy[4] = {1, -1, 0, 0};
    int m = 0, n = 0;
    bool vis[51][51];
 
public:
    int cutOffTree(vector<vector<int>>& forest) {
        m = forest.size(), n = forest[0].size();
        map<int, pair<int,int>> hash; // 数组值和下标，按数组值排序
        for(int i = 0; i < m; ++i)
        {
            for(int j = 0; j < n; ++j)
            {
                if(forest[i][j] > 1) // 0不可走，1是地面
                    hash[forest[i][j]] = {i, j};
            }
        }
        int ret = 0;
        pair<int,int> start = make_pair(0, 0);
        for(auto& [e, end] : hash) // 取下标
        {
            int step = bfs(forest, start, end);
            if(step == -1)
                return -1;
            ret += step;
            start = end;
        }
        return ret;
    }
 
    int bfs(vector<vector<int>>& forest, pair<int,int> start, pair<int,int> end)
    {
        if(start == end)
            return 0;
        memset(vis, 0, sizeof(vis)); // 清空之前的数据
        queue<pair<int, int>> q;
        q.push(start);
        auto [a, b] = q.front();
        vis[a][b] = true;
        int ret = 0;
        while(!q.empty())
        {
            ++ret;
            int sz = q.size();
            while(sz--)
            {
                auto [a, b] = q.front();
                q.pop();
                for(int i = 0; i < 4; ++i)
                {
                    int x = a + dx[i], y = b + dy[i];
                    if(x >= 0 && x < m && y >= 0 && y < n && forest[x][y] && !vis[x][y])
                    {
                        if(x == end.first && y == end.second)
                            return ret;
                        q.push({x, y});
                        vis[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
};